class Solution {
    public void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
    void AdjustDown(int[] nums, int pos, int len) {
        int parent = pos, child = parent * 2 + 1;
        while (child < len) {
            if (child + 1 < len && nums[child] > nums[child + 1]) child += 1;
            if (nums[parent] > nums[child]) {
                swap(nums, parent, child);
                parent = child;
                child = 2 * parent + 1;
            }
            else break;
        }
    }

    public int findKthLargest(int[] nums, int k) {
        for (int i = k / 2 - 1; i >= 0; i--) {
            AdjustDown(nums, i, k);
        }

        for (int i = k; i < nums.length; i++) {
            if (nums[0] < nums[i]) {
                swap(nums, 0, i);
                AdjustDown(nums, 0, k);
            }
        }
        return nums[0];
        
    }
}
